<!--
 * @Description: 新建抽奖活动 - 配置页面
 * @Author: liyujie
 * @Date: 2021/02/07
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/02/18
-->
<template>
    <div class="wrapper">
        <div class="content-wrapper">
            <!-- header -->
            <!-- title -->
            <div class="header">
                {{ type === 'add' ? '新建活动' : type === 'edit' ? '编辑活动' : '查看活动' }}
            </div>
            <!-- /header -->
            <div class="form-wrapper">
                <el-form
                    :model="ruleForm"
                    :rules="rules"
                    ref="ruleForm"
                    label-width="110px"
                    class="el-form-wrap"
                    @submit.native.prevent
                >
                    <div class="form-title">
                        活动页面配置
                    </div>
                    <el-form-item
                        label="活动页背景图"
                        prop="page_config.background_images"
                        class="is-required"
                    >
                        <div class="form-tips">
                            尺寸：宽750px；支持jpg、jpeg、png，请注意图片顺序
                            <span
                                class="preview-btn"
                                @click="showDialog(1)"
                            >
                                查看示例
                            </span>
                        </div>
                        <div class="pic-view">
                            <div
                                class="pic-list"
                            >
                                <draggable
                                    v-model="ruleForm.page_config.background_images"
                                    draggable=".pic-item"
                                    style="display: flex; flex-wrap: wrap"
                                    :disabled="type === 'detail'"
                                    @change="$message.success('排序成功')"
                                >
                                    <div
                                        class="pic-item"
                                        v-for="(item,index) in ruleForm.page_config.background_images"
                                        :key="index"
                                    >
                                        <img
                                            :src="item.url"
                                        >
                                        <div class="img-action">
                                            <i
                                                class="el-icon-zoom-in"
                                                @click="fnShowPreview(item.url)"
                                            />
                                            <i
                                                class="el-icon-delete"
                                                @click="handleDeleteImage(index)"
                                                v-if="type !== 'detail'"
                                            />
                                        </div>
                                    </div>
                                    <el-upload
                                        action="noAction"
                                        :show-file-list="false"
                                        :http-request="handleUploadImage"
                                        :before-upload="beforeUploadImage"
                                        accept="image/*"
                                        :limit="9"
                                        multiple
                                        v-if="ruleForm.page_config.background_images.length < 9"
                                        :disabled="type === 'detail'"
                                    >
                                        <div class="uploader-customer pic-item">
                                            <i class="el-icon-plus"/>
                                            <div class="upload-text">添加图片</div>
                                        </div>
                                    </el-upload>
                                </draggable>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item
                        label="转盘图"
                        prop="page_config.turntable_image"
                        class="required"
                    >
                        <div class="form-tips">
                            尺寸：建议660*660px；支持jpg、jpeg、png
                            <span
                                class="preview-btn"
                                @click="showDialog(2)"
                            >
                                查看示例
                            </span>
                        </div>
                        <image-upload
                            v-model="ruleForm.page_config.turntable_image"
                            :type="type"
                        />
                    </el-form-item>
                    <el-form-item
                        prop="page_config.turntable_top"
                    >
                        <el-input
                            v-model.number="ruleForm.page_config.turntable_top"
                            placeholder="请输入转盘距离背景图顶部的高度，以750px设计稿为准"
                            size="medium"
                            type="number"
                            :style="{width: '240px'}"
                            :disabled="type === 'detail'"
                        >
                            <span slot="suffix">px</span>
                        </el-input>
                        <span
                            class="form-tips"
                            style="margin-left: 12px"
                        >转盘距离背景图顶部的高度，以750px设计稿为准</span>
                    </el-form-item>
                    <el-form-item
                        label="转盘箭头"
                        prop="page_config.turntable_hand_image"
                        class="required"
                    >
                        <div class="form-tips">
                            尺寸：建议220*220px；支持jpg、jpeg、png
                            <span
                                class="preview-btn"
                                @click="showDialog(2)"
                            >
                                查看示例
                            </span>
                        </div>
                        <image-upload
                            v-model="ruleForm.page_config.turntable_hand_image"
                            :type="type"
                        />
                    </el-form-item>
                </el-form>
                <preview-phone
                    class="preview-phone"
                    :page_config="ruleForm.page_config"
                />
            </div>

            <!-- button -->
            <div class="footer">
                <el-button
                    size="medium"
                    type="default"
                    :style="{width: '120px', marginBottom: '52px'}"
                    @click="toLuckDrawEdit"
                >
                    上一步
                </el-button>
                <el-button
                    size="medium"
                    type="primary"
                    :style="{width: '120px', marginBottom: '52px', marginLeft: '32px'}"
                    v-if="type !== 'detail'"
                    @click="handleSave"
                >
                    保存
                </el-button>
                <el-button
                    size="medium"
                    type="primary"
                    :style="{width: '120px', marginBottom: '52px', marginLeft: '32px'}"
                    v-if="type === 'detail'"
                    @click="handleRoute('luckDrawList');"
                >
                    返回列表
                </el-button>
            </div>
        </div>

        <el-dialog
            title="查看示例"
            :visible.sync="dialogVisible"
            width="780px"
        >
            <div class="left">
                <div class="ex-title">完整的转盘视觉效果图</div>
                <img src="@/assets/image/luck-draw/page.png">
            </div>
            <div class="right">
                <template v-if="dialogType === 1">
                    <div class="ex-title">背景图示例</div>
                    <div class="img-item">
                        <img src="@/assets/image/luck-draw/bg-1.png">
                        <span class="img-text">图一</span>
                    </div>
                    <div class="img-item">
                        <img src="@/assets/image/luck-draw/bg-2.png">
                        <span class="img-text">图一</span>
                    </div>
                    <div class="img-item">
                        <img src="@/assets/image/luck-draw/bg-3.png">
                        <span class="img-text">图一</span>
                    </div>
                </template>
                <template v-if="dialogType === 2">
                    <div class="ex-title">转盘和转盘箭头图示例</div>
                    <div class="img-item wheel">
                        <img src="@/assets/image/luck-draw/wheel.png">
                        <span class="img-text">转盘图</span>
                    </div>
                    <div class="img-item point">
                        <img src="@/assets/image/luck-draw/point.png">
                        <span class="img-text">转盘箭头图</span>
                    </div>
                </template>
            </div>

        </el-dialog>
        <!-- 图片预览 -->
        <img-preview ref="preview"/>
    </div>
</template>

<script>
import {back} from '@/mixin/back';
import PreviewPhone from "@/components/luck-draw/preview-phone";
import ImageUpload from "@/components/common/image-upload";
import imgPreview from '@/components/common/img-preview';
import draggable from 'vuedraggable';
const numberReg = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/;

export default {
    name: 'LuckDrawConfig',
    mixins: [back],
    components: {ImageUpload, PreviewPhone,imgPreview,draggable},
    data() {
        return {
            // add新建 edit编辑 detail查看详情
            type: 'add',
            submitForm: {},
            ruleForm: {
                lottery_no: '',
                page_config: {
                    background_images: [],
                    // 轮盘图片
                    turntable_image: '',
                    // 轮盘上边距
                    turntable_top: 320,
                    // 指针图片
                    turntable_hand_image: '',
                }
            },
            rules: {
                'page_config.background_images': [
                    {required: true, message: '请上传页面背景图片', trigger: 'change'}
                ],
                'page_config.turntable_image': [
                    {required: true, message: '请上传轮盘图片', trigger: 'change'}
                ],
                'page_config.turntable_top': [
                    {pattern: numberReg, message: '轮盘上边距必须为数字', trigger: 'blur'}
                ],
                'page_config.turntable_hand_image': [
                    {required: true, message: '请上传指针图片', trigger: 'change'}
                ],
            },
            dialogVisible: false,
            dialogType: 1,
            promiseList: [],
            authResult: {}
        };
    },
    computed: {},
    mounted() {
        this.init();
    },
    watch: {},
    filters: {},

    methods: {

        /**
         * 初始化
         */
        init() {
            let query = this.$route.query;

            this.$store.commit('SET_HEADER', [
                {title: "APP后台"}, {title: '商城'}, {title: '抽奖活动', path: '/student/luck-draw-list'},
                {title: query.type === 'add' ? '新建活动' : query.type === 'edit' ? '编辑活动' : '查看活动'}
            ]);
            this.type = query.type;
            this.ruleForm.lottery_no = query.no;
            this.authResult = this.$route.meta.authResult;
            this.getDetailData();
        },

        /**
         * 获取详情数据
         */
        getDetailData() {
            this.$post('/student/shop_tool%5Clottery%5Cget', {lottery_no: this.ruleForm.lottery_no}, resp => {
                if (resp.code === 1) {
                    this.submitForm = resp.data;
                    if(resp.data.page_config && JSON.stringify(resp.data.page_config) !== '[]') {
                        this.ruleForm.page_config = resp.data.page_config;
                    } else {
                        this.ruleForm.page_config = {
                            background_images: [],
                            turntable_image: '',
                            turntable_top: 320,
                            turntable_hand_image: '',
                        };
                    }
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        type: 'warning',
                        duration: 2000
                    });
                }
            });
        },

        /**
         * 上一步 跳转编辑页面
         */
        toLuckDrawEdit() {
            let query = this.$route.query;

            // 如果是草稿状态 上一步保存草稿
            if(this.submitForm.status === 0) {
                this.handleSubmit('prev');
            } else {
                this.handleRoute('luckDrawEdit', {no: query.no, type: query.type, status: query.status});
            }
        },

        /**
         * 保存
         */
        handleSave() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    this.handleSubmit('save');
                }
            });
        },

        /**
         * 提交
         * @param type prev上一步  save保存
         */
        handleSubmit(type) {
            let params = {...this.submitForm};
            let query = this.$route.query;

            params.page_config = JSON.stringify(this.ruleForm.page_config);
            params.item_list = JSON.stringify(params.item_list);
            params.only_save = type === 'prev' ? 1 : 0;
            params.lottery_no = this.ruleForm.lottery_no;
            this.$post('/student/shop_tool%5Clottery%5Csave', params, resp => {
                if (resp.code === 1) {
                    if(type === 'prev') {
                        this.handleRoute('luckDrawEdit', {no: query.no, type: query.type, status: query.status});
                    } else {
                        this.$notify({
                            title: '提示',
                            message: '保存成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.handleRoute('luckDrawList');
                    }
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        type: 'warning',
                        duration: 2000
                    });
                }
            });
        },

        /**
         * 路由跳转
         * @param routeName
         * @param query
         */
        handleRoute(routeName, query) {
            this.$router.push({
                name: routeName,
                query
            });
        },

        /**
         * 上传图片
         * @param e
         * @param success
         * @param error
         */
        uploadImage(e, success, error) {
            let pic = new FormData();

            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                success: resp => {
                    if (resp.code === 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        /**
         * 删除上传的图片
         * @param index
         */
        handleDeleteImage(index) {
            this.ruleForm.page_config.background_images.splice(index, 1);
        },

        /**
         * 预览图片
         * @param   {String}    images      //单图预览
         * @param   {Array}     images      //多图预览
         * @param index
         */
        fnShowPreview(images, index) {
            if (images && Object.prototype.toString.call(images) == '[object String]') {
                this.$refs.preview.show([
                    images
                ]);
            } else if (images && Object.prototype.toString.call(images) == '[object Array]') {
                this.$refs.preview.show(images, index);
            } else {
                this.$message({
                    type: 'warning',
                    message: '图片类型错误'
                });
            }
        },

        /**
         * 上传详情图片
         * @param e
         * @returns {boolean}
         */
        handleUploadImage(e) {
            this.uploadImage(e, (resp) => {
                if (this.ruleForm.page_config.background_images.length >= 9) {
                    this.$notify({
                        title: '提示',
                        message: '最多只可以上传9张图片',
                        type: 'warning',
                        duration: 2000
                    });
                    return false;
                }
                this.getImageSize(resp.data.url).then(res => {
                    this.ruleForm.page_config.background_images = [...this.ruleForm.page_config.background_images, res];
                });
            }, (resp) => {
                console.log(resp.msg);
            });
        },

        /**
         * 上传图片之前 图片大小限制
         * @param file
         * @returns {boolean}
         */
        beforeUploadImage(file) {
            let type = ['image/jpeg', 'image/png', 'image/jpg'],
                isType = type.includes(file.type),
                isLt2M = file.size / 1024 < 200;

            if (!isType) {
                this.$notify({
                    title: '提示',
                    message: '格式仅支持jpg、jpeg、png',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }

            /*if (!isLt2M) {
                this.$notify({
                    title: '提示',
                    message: '图片大小不能超过200KB',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }*/

            return isType;
        },

        /**
         * 显示示例弹窗
         * @param type
         */
        showDialog(type) {
            this.dialogType = type;
            this.dialogVisible = true;
        },

        /**
         * 获取图片宽高
         * @param url
         * @returns {Promise<unknown>}
         */
        getImageSize (url) {
            return new Promise((resolve, reject) => {
                let imgObj = new Image();

                imgObj.src = url;
                imgObj.onload = () => {
                    resolve({
                        url,
                        width: imgObj.width,
                        height: imgObj.height
                    });
                };
            });
        }
    }
};
</script>

<style lang="less" scoped>
.wrapper {
    width: 100%;

    .content-wrapper {
        display: flex;
        flex-direction: column;
        position: relative;
        margin: 12px;
        background: #fff;
        box-sizing: border-box;
        overflow: auto;

        /*header*/
        .header {
            width: 100%;
            height: 68px;
            display: flex;
            align-items: center;
            white-space: nowrap;
            box-sizing: border-box;
            padding-left: 35px;
            color: rgba(51, 51, 51, 1);
            font-size: 20px;
            font-weight: 500;
            position: relative;
            border-bottom: 1px rgba(233, 233, 233, 1) solid;
            &::before {
                content: '';
                background: rgba(24, 144, 255, 1);
                width: 3px;
                height: 20px;
                position: absolute;
                top: 23px;
                left: 25px;
            }
        }

        // 表单
        .form-wrapper {
            background: #FBFBFB;
            border: 1px solid #EEEEEE;
            padding: 20px 32px;
            margin: 24px;
            min-height: 819px;
            position: relative;

            .form-title {
                font-size: 16px;
                font-family: PingFangSC-Semibold, PingFang SC;
                font-weight: 600;
                color: #333333;
                border-bottom: 1px solid #E9E9E9;
                padding: 12px 0;
                margin-bottom: 24px;
            }
            .preview-btn {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #20A0FF;
                text-decoration: underline;
                cursor: pointer;
                margin-left: 12px;
            }
            .form-tips {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #999999;
            }
            .preview-phone {
                position: absolute;
                right: 32px;
                top: 96px;
                box-shadow: 0 0 20px 0 rgba(110, 117, 126, 0.62);
            }
            .pic-view {
                margin-top: 12px;
                .pic-list {
                    max-width: 680px;
                    display: flex;
                    flex-wrap: wrap;
                    align-items: center;
                }
            }

            .pic-item {
                width: 100px;
                height: 100px;
                overflow: hidden;
                border-radius: 4px;
                margin-right: 16px;
                margin-bottom: 16px;
                position: relative;

                img {
                    width: 100%;
                    height: 100%;
                    border-radius: 4px;
                }

                .img-action {
                    position: absolute;
                    left: 0;
                    top: 0;
                    z-index: 1;
                    width: 100px;
                    height: 100px;
                    border-radius: 4px;
                    background: rgba(0, 0, 0, .6);
                    justify-content: center;
                    align-items: center;
                    display: none;

                    i {
                        color: #ffffff;
                        font-size: 17px;
                        cursor: pointer;
                    }

                    .el-icon-delete {
                        margin-left: 17px;
                    }
                }

                &:hover {
                    .img-action {
                        display: flex;
                    }
                }
            }
            .uploader-customer {
                width: 100px;
                height: 100px;
                background: rgba(242, 242, 242, 1);
                display: flex;
                justify-content: center;
                align-items: center;
                flex-direction: column;
                color: #999;
                padding-top: 12px;
                position: relative;
                border-radius: 4px;
                overflow: hidden;
                border: 1px dashed #aaa;

                i {
                    font-size: 20px;
                }

                .video-cover {
                    width: 100px;
                    height: 100px;
                    position: absolute;
                    left: 0;
                    top: 0;
                }

                .img-action {
                    position: absolute;
                    left: 0;
                    top: 0;
                    z-index: 1;
                    width: 100px;
                    height: 100px;
                    border-radius: 4px;
                    background: rgba(0, 0, 0, .6);
                    justify-content: center;
                    align-items: center;
                    display: none;

                    i {
                        color: #ffffff;
                        font-size: 17px;
                        cursor: pointer;
                    }

                    .el-icon-delete {
                        margin-left: 17px;
                    }
                }

                &:hover {
                    .img-action {
                        display: flex;
                    }
                }

                .progress {
                    padding: 12px;
                    box-sizing: border-box;
                    position: absolute;
                    left: 0;
                    top: 0;
                    z-index: 1;
                    width: 100px;
                    height: 100px;
                    border-radius: 4px;
                    background: rgba(0, 0, 0, .6);

                    /deep/ .el-progress {
                        margin-top: 50%;
                        transform: translateY(-50%);

                        .el-progress-bar__outer {
                            background: rgba(255, 255, 255, .2);
                        }
                    }

                }
            }
        }

        .footer {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 8px;
        }

        /deep/ .el-form {
            .el-form-item__content {
                max-width: 70%;
            }
            .is-required {
                .el-form-item__label {
                    &:before {
                        content: "*";
                        display: inline-block;
                        color: #F56C6C;
                        margin-right: 4px;
                    }
                }
            }
        }
    }

    /deep/ .el-dialog__body {
        padding: 24px 68px;
        display: flex;
        justify-content: center;
        .ex-title {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #333333;
            margin-bottom: 15px;
        }
        img {
            width: 220px;
        }
        .left {
            margin-right: 56px;
            img {
                width: 240px;
            }
        }
        .right {
            .img-item {
                display: flex;
                align-items: center;
                img {
                    margin-bottom: 20px;
                }
                .img-text {
                    margin-left: 12px;
                }
                &.wheel {
                    img {
                        width: 190px;
                        margin-bottom: 33px;
                        border: 1px solid #E7E7E7;
                    }
                }
                &.point {
                    img {
                        width: 74px;
                        border: 1px solid #E7E7E7;
                    }
                }
            }
        }

    }
    /deep/ .el-dialog__header {
        padding-top: 10px;
        box-shadow: 0 1px 0 0 rgba(233, 233, 233, 1);
        display: flex;
        align-items: center;
        background: #FAFAFA;
        border-radius: 4px 4px 0 0;

        .el-dialog__title {
            font-weight: 500;
            color: #333;
            font-size: 14px;
        }

        .el-icon-close:before {
            color: rgb(194, 194, 194);
            font-size: 17px;
            font-weight: bold;
        }

        .el-dialog__headerbtn {
            top: 14px;
        }
    }

    /deep/ .el-textarea__inner {
        resize: none;
    }
    /deep/ .el-input__suffix {
        margin-right: 6px;
    }
}
</style>
